package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
@Component
public class RedisLockUtil {

    /**
     * 获取互斥锁
     *
     * @param key
     * @param stringRedisTemplate
     * @return
     */
    public static boolean tryLock(String key, StringRedisTemplate stringRedisTemplate) {
        //获取互斥锁
        Boolean LockFlag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 5, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(LockFlag);//使用BooleanUtil工具类判断是否获取到锁
    }

    /**
     * 释放互斥锁
     *
     * @param key
     * @param stringRedisTemplate
     */
    public static void unLock(String key, StringRedisTemplate stringRedisTemplate) {
        //释放互斥锁
        stringRedisTemplate.delete(key);
    }
}
